package com.res.share.controller;


import com.alibaba.fastjson.JSON;
import com.res.share.common.WebResponse;
import com.res.share.common.utils.MD5utils;
import com.res.share.common.utils.StringUtils;
import com.res.share.common.utils.httpUtils.HttpParamers;
import com.res.share.common.utils.httpUtils.HttpRequestUtils;
import com.res.share.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * https://xorpay.com/
 */
@Controller
@RequestMapping("/res-order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    public final static String aid = "20640";

    public final static String app_secret = "6b089a9da25747b8a49d3fa0942f1ddf";

    /**
     * 下单
     *
     * @param orderPrice
     * @return
     */
    @PostMapping("/goToCreateOrder")
    @ResponseBody
    public WebResponse goToCreateOrder(@RequestParam("orderPrice") String orderPrice) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            //创建订单 TODO
            String name = null;//商品名称
            String pay_type = "native";//支付类型，默认native
            String price = null;//支付价格
            String order_id = null;//订单ID
            String order_uid = null;//用户id
            String notify_url = null;//回调地址  回调地址必须为网络地址
            String sign = MD5utils.generate(name + pay_type + price + order_id + notify_url + app_secret);
            HttpParamers httpParamers = HttpParamers.httpPostParamers();
            httpParamers.addParam("name", name);//商品名称
            httpParamers.addParam("pay_type", pay_type);//支付类型，默认native
            httpParamers.addParam("price", price);//支付价格
            httpParamers.addParam("order_id", order_id);//订单ID
            httpParamers.addParam("order_uid", order_uid);//用户id
            httpParamers.addParam("notify_url", notify_url);//回调地址  回调地址必须为网络地址
            httpParamers.addParam("sign", sign);
            HttpRequestUtils httpRequestUtils = new HttpRequestUtils("https://xorpay.com");
            String resultJson = httpRequestUtils.service("api/pay/" + aid, httpParamers);
            if (StringUtils.isNotEmpty(resultJson)) {
                Map map = JSON.parseObject(resultJson, Map.class);
                if (map != null) {
                    /**
                     * ok 成功
                     * no_contract 未签约
                     * no_alipay_contract 未签约支付宝
                     * missing_argument 缺少参数
                     * app_off 账号被冻结
                     * aid_not_exist aid不存在
                     * pay_type_error 支付类型错误
                     * sign_error 签名错误
                     * order_payed 订单已支付
                     * order_expire 订单过期
                     * alipay_api_error 并且 info 是 ACQ.ACCESS_FORBIDDEN 表示需要去支付宝发来的邮件里面点签约
                     * alipay_api_error 并且 info 是 aop.invalid-app-auth-token 联系客服处理
                     * fee_error 余额不足
                     * order_exist 同一订单，参数不同
                     */
                    if(map.get("status")!=null && map.get("status").toString().equalsIgnoreCase("ok")){
                        resultMap.put("status",1);
                        resultMap.put("msg","下单成功");
                        resultMap.put("expireIn",map.get("expire_in"));//订单过期秒数
                        resultMap.put("qrCode",map.get("info"));
                    }else {
                        resultMap.put("status",2);
                        resultMap.put("msg","网络链接异常,请稍后重试!");
                        //异步发送邮件 TODO
                    }
                } else {
                    resultMap.put("status",2);
                    resultMap.put("msg","网络链接异常,请稍后重试!");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("status",2);
            resultMap.put("msg","网络链接异常,请稍后重试!");
        }
        return WebResponse.ok(resultMap);
    }


    /**
     * aoid	string	XorPay 平台订单唯一标识
     * order_id	string	你传入的 order_id 参数
     * pay_price	float	例如: 50.00
     * pay_time	string	例如: 2019-01-01 00:00:00
     * more	string	订单传过来的其他信息
     * detail	string	json格式，订单支付详细信息
     * transaction_id 渠道流水号
     * bank_type 用户付款方式
     * buyer 消费者
     * sign	string	签名, 参数 aoid + order_id + pay_price + pay_time + app secret 顺序拼接后 MD5
     * @param request
     * @return
     */
    @RequestMapping(value = "/orderCallback",method = RequestMethod.POST)
    public ResponseEntity orderCallback(HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<>();
        String aoid = request.getParameter("aoid");
        String orderId = request.getParameter("order_id");//你传入的 order_id 参数
        String payPrice = request.getParameter("pay_price");
        String payTime = request.getParameter("pay_time");
        String more = request.getParameter("more");
        String detail = request.getParameter("detail");
        String transactionId = request.getParameter("transaction_id");
        String bankType = request.getParameter("bank_type");
        String buyer = request.getParameter("buyer");
        String sign = request.getParameter("sign");
        //验证信息
        /**
         * 当你收到回调请求后，如果响应HTTP 200(可以返回 ok/success 等字符)那么 XorPay 会认为通知成功，否则如果返回 HTTP 400/404/500 等其他状态码会认为通知失败，
         * 会再次通知 6 次，间隔为 1/2/4/16/64/300 分钟。
         */

        ResponseEntity<String> resp = ResponseEntity
                .ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body("");

        return resp;
    }


    /**
     * 查询订单状态
     * @param orderId
     * @return
     */
    @PostMapping("/findOrderStatus")
    @ResponseBody
    public WebResponse findOrderStatus(@RequestParam("orderId") String orderId) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            String sign = MD5utils.generate(orderId + app_secret);
            HttpParamers httpParamers = HttpParamers.httpPostParamers();
            httpParamers.addParam("order_id", orderId);//订单ID
            httpParamers.addParam("sign", sign);
            HttpRequestUtils httpRequestUtils = new HttpRequestUtils("https://xorpay.com");
            String resultJson = httpRequestUtils.service("api/query2/" + aid, httpParamers);
            if (StringUtils.isNotEmpty(resultJson)) {
                Map map = JSON.parseObject(resultJson, Map.class);
                if (map != null) {
                    /**
                     * not_exist 订单不存在
                     * new 订单未支付
                     * payed 订单已支付，未通知成功
                     * fee_error 手续费扣除失败
                     * success 订单已支付，通知成功
                     * expire 订单过期
                     */
                    if(map.get("status").toString().equalsIgnoreCase("payed")
                            || map.get("status").toString().equalsIgnoreCase("success") ) {
                        resultMap.put("status",1);
                        resultMap.put("msg","订单已支付");
                    }else if(map.get("status").toString().equalsIgnoreCase("new") ) {
                        resultMap.put("status",2);
                        resultMap.put("msg","订单未支付");
                    }else if(map.get("status").toString().equalsIgnoreCase("not_exist") ) {
                        resultMap.put("status",3);
                        resultMap.put("msg","订单不存在");
                    }else if(map.get("status").toString().equalsIgnoreCase("expire") ) {
                        resultMap.put("status",4);
                        resultMap.put("msg","订单过期");
                    }
                } else {
                    resultMap.put("status",5);
                    resultMap.put("msg","网络链接异常,请稍后重试!");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("status",5);
            resultMap.put("msg","网络链接异常,请稍后重试!");
        }
        return WebResponse.ok(resultMap);
    }
}
